//go:build windows
// +build windows

package win

import (
	"syscall"
	"unsafe"
)

var (
	// Library
	libkernel32 uintptr

	// Functions
	closeHandle            uintptr
	fileTimeToSystemTime   uintptr
	getConsoleTitle        uintptr
	getConsoleWindow       uintptr
	getLastError           uintptr
	getLocaleInfo          uintptr
	getLogicalDriveStrings uintptr
	getModuleHandle        uintptr
	getNumberFormat        uintptr
	getThreadLocale        uintptr
	getThreadUILanguage    uintptr
	getVersion             uintptr
	globalAlloc            uintptr
	globalFree             uintptr
	globalLock             uintptr
	globalUnlock           uintptr
	moveMemory             uintptr
	mulDiv                 uintptr
	setLastError           uintptr
	systemTimeToFileTime   uintptr
	getProfileString       uintptr

	getCurrentProcess uintptr

	winExec uintptr
	// codyguo
	openProcess uintptr
)

func kernel32_init() {
	// Library
	libkernel32 = MustLoadLibrary("kernel32.dll")

	// Functions
	closeHandle = MustGetProcAddress(libkernel32, "CloseHandle")
	fileTimeToSystemTime = MustGetProcAddress(libkernel32, "FileTimeToSystemTime")
	getConsoleTitle = MustGetProcAddress(libkernel32, "GetConsoleTitleW")
	getConsoleWindow = MustGetProcAddress(libkernel32, "GetConsoleWindow")
	getLastError = MustGetProcAddress(libkernel32, "GetLastError")
	getLocaleInfo = MustGetProcAddress(libkernel32, "GetLocaleInfoW")
	getLogicalDriveStrings = MustGetProcAddress(libkernel32, "GetLogicalDriveStringsW")
	getModuleHandle = MustGetProcAddress(libkernel32, "GetModuleHandleW")
	getNumberFormat = MustGetProcAddress(libkernel32, "GetNumberFormatW")
	getProfileString = MustGetProcAddress(libkernel32, "GetProfileStringW")
	getThreadLocale = MustGetProcAddress(libkernel32, "GetThreadLocale")
	getThreadUILanguage, _ = syscall.GetProcAddress(syscall.Handle(libkernel32), "GetThreadUILanguage")
	getVersion = MustGetProcAddress(libkernel32, "GetVersion")
	globalAlloc = MustGetProcAddress(libkernel32, "GlobalAlloc")
	globalFree = MustGetProcAddress(libkernel32, "GlobalFree")
	globalLock = MustGetProcAddress(libkernel32, "GlobalLock")
	globalUnlock = MustGetProcAddress(libkernel32, "GlobalUnlock")
	moveMemory = MustGetProcAddress(libkernel32, "RtlMoveMemory")
	mulDiv = MustGetProcAddress(libkernel32, "MulDiv")
	setLastError = MustGetProcAddress(libkernel32, "SetLastError")
	systemTimeToFileTime = MustGetProcAddress(libkernel32, "SystemTimeToFileTime")

	getCurrentProcess = MustGetProcAddress(libkernel32, "GetCurrentProcess")

	winExec = MustGetProcAddress(libkernel32, "WinExec")
	//codyguo
	openProcess = MustGetProcAddress(libkernel32, "OpenProcess")
}

func WinExec(cmdLine string, uCmdShow uint32) uint32 {
	lpCmdLine := StringToBytePtr(cmdLine)
	ret, _, _ := syscall.Syscall(winExec,
		2,
		uintptr(unsafe.Pointer(lpCmdLine)),
		uintptr(uCmdShow),
		0)

	return uint32(ret)
}
